package com.mata.worktime.configuration.shiro.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.mata.worktime.constant.ShiroConstants;
import com.mata.worktime.constant.UserConstants;
import com.mata.worktime.entity.user.User;
import com.mata.worktime.enums.ResultEnum;
import com.mata.worktime.enums.UserStatusEnum;
import com.mata.worktime.exception.BaseException;
import com.mata.worktime.service.user.UserService;
import com.mata.worktime.util.ServletUtils;


/**
 * 登录校验方法
 *
 * @author earthchen
 */
@Component
public class LoginService {
    @Autowired
    private PasswordService passwordService;

    @Autowired
    private UserService userService;

    /**
     * 登录
     */
    public User login(String username, String password) {

        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new BaseException(ResultEnum.USERNAME_PASSWORD_NOT_NULL);
        }
        // 查询用户信息
        User user = userService.selectUserByLoginName(username);

        if (user == null && maybeMobilePhoneNumber(username)) {
            user = userService.selectUserByPhoneNumber(username);
        }

        if (user == null && maybeEmail(username)) {
            user = userService.selectUserByEmail(username);
        }

        if (user == null || UserStatusEnum.DELETED.getCode().equals(user.getDelFlag())) {
            throw new BaseException(ResultEnum.USER_STATUS_ERROR);
        }

        // 验证码校验
        if (password.length()==32){

        }else {
            if (!StringUtils.isEmpty(
                    ServletUtils.getRequest().getAttribute(ShiroConstants.CURRENT_CAPTCHA))) {
//                throw new BaseException(ResultEnum.CAPTCHA_ERROR);
            }

            passwordService.validate(user, password);
        }



        if (UserStatusEnum.DISABLE.getCode().equals(user.getStatus())) {
            throw new BaseException(ResultEnum.USER_STATUS_ERROR);
        }
        return user;
    }

    private boolean maybeEmail(String username) {
        return username.matches(UserConstants.EMAIL_PATTERN);
    }

    private boolean maybeMobilePhoneNumber(String username) {
        return username.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN);
    }
}
